import { localStorageUtils } from "assets/js/utils";

export const user = {
  namespaced: true, // 为了解决不同模块的属性和方法命名冲突的问题
  state() {
    return {
      tokenInfoModel: {
        token: "",
        tokenType: "",
        expiration: 0,
        userName: "",
        uId: "",
        refreshTime: "",
        expirationTime: "",
      },
    };
  },
  getters: {},
  mutations: {
    //更新token
    refreshToken(state, token) {
      state.tokenModel.token = token;
    },
    //登陆成功设置用户登录信息
    setUserInformation(state, tokenInfoViewModel) {
      if (!tokenInfoViewModel) {
        for (let key in state.tokenInfoModel) {
          delete state.tokenInfoModel[key];
        }
        localStorageUtils.clear();
        return;
      }
      //存储token信息
      state.tokenInfoModel.token = tokenInfoViewModel.token;
      state.tokenInfoModel.expiration = tokenInfoViewModel.expiration;
      state.tokenInfoModel.userName = tokenInfoViewModel.userName;
      state.tokenInfoModel.uId = tokenInfoViewModel.uId;
      state.tokenInfoModel.expirationTime = new Date(tokenInfoViewModel.expirationTime).toString();
      state.tokenInfoModel.refreshTime = new Date(tokenInfoViewModel.refreshTime).toString();
      state.tokenInfoModel.tokenType = tokenInfoViewModel.tokenType;

      //在sessionStorage中存储一份token信息
      localStorageUtils.set("token", JSON.stringify(state.tokenInfoModel));
    },
  },
  actions: {
    //外面用dispatch调用
    async refreshToken(context, token) {
      context.commit("user/refreshToken", token);
    },
  },
  modules: {},
};
